import React from 'react';
import { RouterList } from '../../router';
import { RouteListRawState } from '../../type';
import { Menu } from 'antd';
import type { MenuProps } from 'antd';
import { useLocation,useNavigate } from 'react-router-dom';
import { UserListRawState } from '../../type';

const GenerateMenu = (
  routers: RouteListRawState[],
  role: string
): MenuProps["items"] => {
  return routers
    .filter((item) => {
      //将路由表中隐藏的路由筛选掉
      if (item.meta.hide) {
        return false;
      }
      return true;
    })
    .filter((item) => {
      //筛选权限 如果role属性不存在表示所有人都能看所以返回真
      if (!item.meta.roles) {
        return true;
      } else {
        //如果roles存在则判断当前路由的权限和登陆权限是否一致
        return item.meta.roles.includes(role);
      }
    })
    .sort((a, b) => {
      //菜单位置排序
      const rankA = a.meta.rank === undefined ? 1 : a.meta.rank;
      const rankB = b.meta.rank === undefined ? 1 : b.meta.rank;

      return rankA - rankB;
    })
    .map((item) => {
      //按照antd menu组件需要的数据返回
      return {
        key: item.path,
        icon: item.meta.icon,
        label: item.meta.label,
        children: item.children && GenerateMenu(item.children, role),
      };
    });
};

const Index:React.FC = () => {
  const { pathname } = useLocation();
  const data = localStorage.getItem("userInfor");
  const userInfor: UserListRawState = JSON.parse(data ? data : "{}");
  //调用生成菜单的方法
  const itemData = GenerateMenu(RouterList, userInfor.role);
  const navigate = useNavigate();

  return (
    <div>
        <Menu
        defaultOpenKeys={["/user"]}
        defaultSelectedKeys={[pathname]}
        selectedKeys={[pathname]}
        theme="light"
        mode="inline"
        items={itemData}
        onSelect={({ key }) => navigate(key)}
      />
    </div>
  )
}

export default Index